#include "grepmanager.h"
#include <QStringList>
#include <QProcess>
#include <QFileInfo>

GrepManager::GrepManager()
{
    m_scrollOffset = 0;
}

QString GrepManager::getHtml()
{
    return m_searchResultsContent;
}

void GrepManager::doSearch(QString aPattern, QStringList & aFiles)
{
    QProcess grep;
    grep.setProcessChannelMode(QProcess::MergedChannels);
    QString cmd("grep -b --color=never -e ");
    cmd += aPattern;
    cmd += " ";
    cmd += aFiles.join(" ");
    grep.start(cmd);
    grep.waitForFinished(-1);
    QByteArray output = grep.readAllStandardOutput();
    QString temp(output);
    QStringList lines = temp.split("\n");

    QStringList content;
    content << "<html>";
    content << "<head>";
    content << "</head>";
    content << "<body>";
    content << "<H1>Search results for " + aPattern + "</H1><br>";
    for(int i = 0; i < lines.count(); i++)
    {
        int colon = lines[i].indexOf(":");
        if(colon < 0)
        {
            content << "<b>" + lines[i] + "</b><br>";
            continue;
        }

        QString path = lines[i].left(colon);
        QString buffer = lines[i].right(lines[i].length() - colon - 1);
        colon = buffer.indexOf(":");
        if(colon < 0)
        {
            content << "<b>" + lines[i] + "</b><br>";
            continue;
        }
        QString sOffset = buffer.left(colon);
        QString message = buffer.right(buffer.length() - colon - 1);
        bool ok = false;
        sOffset.toInt(&ok);
        if(!ok)
        {
            content << "<b>" + lines[i] + "</b><br>";
            continue;
        }

        QFileInfo info(path);
        content << "< a href='goto:" + path + ":" + sOffset + "'>"
                << info.fileName() << "</a> : <b>" << message << "</b><br>";

    }
    content << "</body>";
    content << "</html>";
    m_searchResultsContent = content.join("");

}
